package init

import (
	"fmt"
	"log"
	"pet-server/basic/config"

	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func init() {
	ViperInit()
	MysqlInit()
	RedisInit()
}

func ViperInit() {
	viper.SetConfigFile("../../dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		return
	}
	err = viper.Unmarshal(&config.AppConfig)
	if err != nil {
		return
	}
	log.Println("viper配置成功", config.AppConfig)

}

func MysqlInit() {
	var err error
	mysqlDB := config.AppConfig.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mysqlDB.User, mysqlDB.Password, mysqlDB.Host, mysqlDB.Prot, mysqlDB.Database)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic(err)
	}
	log.Println("mysql连接成功")
}

func RedisInit() {

	redisDB := config.AppConfig.Redis
	addr := fmt.Sprintf("%s:%d", redisDB.Host, redisDB.Port)
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     addr,
		Password: redisDB.Password, // no password set
		DB:       redisDB.DB,       // use default DB
	})

	err := config.Rdb.Set(config.Ctx, "key", "value", 0).Err()
	if err != nil {
		panic(err)
	}

	log.Println("redis连接成功")
}
